//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Core
{
    using System;
    using System.Configuration;

    using Model;
    using PropertyNames = PreflightConfigurationSection.PropertyNames;

    internal class ContextFromConfiguration : ConfigurationSectionReaderBase<PreflightConfigurationSection>
    {
        public static bool EngineConfigurationIsDefined
        {
            get { return new ContextFromConfiguration().ConfigurationExists(); }
        }

        protected override string ConfigurationSectionPath
        {
            get { return "preflight/engine"; }
        }

        public virtual PreflightContext Read()
        {
            var configSection = this.GetSection();
            var options = this.CreateOptions(configSection);
            var factory = this.CreateFactoryInstance(configSection);
            return new PreflightContext(factory, options);
        }

        private IVerificationFactory CreateFactoryInstance(PreflightConfigurationSection configSection)
        {
            var typeName = configSection.GetValue<string>(PropertyNames.VerificationFactoryTypeName);

            try
            {
                return this.CreateInstanceFromConfiguredTypeName<IVerificationFactory>(configSection, PropertyNames.VerificationFactoryTypeName);
            }
            catch (Exception exception)
            {
                Log.LogError("Failed to load verification factory: {0} because {1}", typeName, exception);
                throw new FailedToLoadVerificationFactoryException("Could not load verification factory: " + typeName + ". See inner exception.", exception);
            }
        }

        private PreflightOptions CreateOptions(PreflightConfigurationSection section)
        {
            Log.LogVerbose("Loading configuration...");
            var options = new PreflightOptions();
            try
            {
                section.InvokeActionIfPropertyAvailable<bool>(PropertyNames.EnableResultCaching, value => options.EnableResultCaching = value);
                section.InvokeActionIfPropertyAvailable<int>(PropertyNames.MaximumNumberOfConcurrentRequests, value => options.MaximumNumberOfConcurrentRequests = value);
                section.InvokeActionIfPropertyAvailable<TimeSpan>(PropertyNames.ResultCachingDuration, value => options.ResultCachingDuration = value);
                section.InvokeActionIfPropertyAvailable<TimeSpan>(PropertyNames.VerificationTimeout, value => options.VerificationTimeout = value);
                section.InvokeActionIfPropertyAvailable<bool>(PropertyNames.SequentialMode, value => options.SequentialMode = value);
                section.InvokeActionIfPropertyAvailable<bool>(PropertyNames.SequentialMode, value => options.SequentialMode = value);
                section.InvokeActionIfPropertyAvailable<int>(PropertyNames.MessagingLevel, value => options.MessagingLevel = (MessagingLevel)value);
            }
            catch (Exception exception)
            {
                Log.LogError("Loading configuration failed with this exception: {0}", exception);
                throw new FailedToLoadEngineConfigurationException(exception);
            }

            Log.LogInformation("Options loaded. Values: {0}", options);
            return options;
        }
    }
}
